package cn.myfirefly.sso.authentication.principal;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.jasig.services.persondir.IPersonAttributeDao;

public final class CompanyCredentialsToPrincipalResolver implements CredentialsToPrincipalResolver {
	/** Logging instance. */
    private final Log log = LogFactory.getLog(getClass());
    
    private IPersonAttributeDao attributeRepository;
    
	@SuppressWarnings("deprecation")
	public Principal resolvePrincipal(Credentials credentials) {
		final CompanyCredentials xhPortalCredentials = (CompanyCredentials) credentials;

        if (log.isDebugEnabled()) {
            log.debug("Creating SimplePrincipal for ["
                + xhPortalCredentials.getUsername() + "]");
        }
        

        final Map<String, Object> personMap = attributeRepository.getUserAttributes(xhPortalCredentials.getUsername());
        
        if (log.isDebugEnabled()) {
            log.debug("query person's attrbuites for ["
                + xhPortalCredentials.getUsername() + "]:" + personMap);
        }
        
        return new SimplePrincipal(xhPortalCredentials.getUsername(), personMap);
	}

	public boolean supports(Credentials credentials) {
		return credentials != null
	             && CompanyCredentials.class.isAssignableFrom(credentials
	                 .getClass());
	}

	public IPersonAttributeDao getAttributeRepository() {
		return attributeRepository;
	}

	public void setAttributeRepository(IPersonAttributeDao attributeRepository) {
		this.attributeRepository = attributeRepository;
	}
}
